import 'package:cloud_medicine/components/tag.dart';
import 'package:cloud_medicine/components/user_avatar.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/chat_api.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/model/base_user_info.dart';
import 'package:cloud_medicine/model/chat_list.dart';
import 'package:cloud_medicine/pages/chat_detail.dart';
import 'package:cloud_medicine/pages/search_chat.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:left_scroll_actions/left_scroll_actions.dart';

class ChatListPage extends StatefulWidget {
  @override
  _ChatListPageState createState() => _ChatListPageState();
}

class _ChatListPageState extends State<ChatListPage> {
  List<ChatItem> _chatList = [];
  bool showLoading = false; // 加载状态

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  // 请求并更新数据
  _updateData() async {
    _chatList.clear();
    dynamic res = await getChatList_api('$backIP/chat/list');
    if (res['code'] == 0) {
      res['data'].forEach((dynamic chatItem) {
        if (mounted) {
          setState(() {
            ChatItem chatItemModel = ChatItem.init(chatItem);
            _chatList.add(chatItemModel);
          });
        }
      });
    } else {
      errorToast(res['message']);
    }
    if (mounted) {
      setState(() {
        showLoading = false;
      });
    }
  }

  // 加载数据
  Future<Null> _loadData() async {
    if (user == null) {
      Fluttertoast.showToast(
        msg: '请先登录',
        backgroundColor: Colors.black,
        textColor: Colors.white,
      );
      return;
    }
    setState(() {
      showLoading = true;
    });
    _updateData();
  }

  _judgeReadNum(int unreadNum) {
    if (unreadNum > 0) {
      return Container(
        width: 20,
        height: 20,
        alignment: Alignment(0, 0),
        decoration: new BoxDecoration(
          color: Colors.grey,
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          border: new Border.all(width: 1, color: Colors.grey),
        ),
        child: Text(
          unreadNum.toString(),
          style: TextStyle(color: Colors.white, fontSize: 10),
        ),
      );
    } else {
      return Container();
    }
  }

  // 移除聊天
  _removeChat(index, id) async {
    setState(() {
      _chatList.removeAt(index);
    });
    dynamic res = await removeChat_api({'chat_id': id});
    res['code'] == 0 ? successToast('移除聊天成功') : errorToast(res['message']);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: Text('聊天列表'),
        centerTitle: true,
        automaticallyImplyLeading: false,
      ),
      body: ListView(
        children: <Widget>[
          GestureDetector(
            child: Container(
              margin: EdgeInsets.all(10),
              alignment: Alignment(0, 0),
              height: 30,
              width: 300,
              decoration: new BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(25.0)),
                border: new Border.all(width: 1, color: Colors.white),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Icon(Icons.search, color: Colors.grey),
                  Text('搜索', style: TextStyle(color: Colors.grey))
                ],
              ),
            ),
            onTap: () {
              Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => SearchChatPage()));
            },
          ),
          ListView.builder(
            shrinkWrap: true,
            physics: new NeverScrollableScrollPhysics(),
            padding: new EdgeInsets.all(5.0),
            itemCount: _chatList.length + 1,
            itemBuilder: (BuildContext context, int index) {
              int openPrescriptionStatus = 0;
              if (index != _chatList.length) {
                openPrescriptionStatus =
                    _chatList[index].openPrescriptionStatus;
              }
              if (index == _chatList.length) {
                return loadingWidget(showLoading);
              }
              return LeftScroll(
                buttonWidth: 80,
                child: Material(
                  child: InkWell(
                    child: Container(
                      margin: EdgeInsets.only(bottom: 5, top: 5),
                      height: 60,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          SizedBox(width: 10),
                          UserAvatar(
                            userID: _chatList[index].authorBasicInfo.id,
                            avatar: _chatList[index].authorBasicInfo.avatar,
                            imageStyle: 60,
                          ),
                          SizedBox(width: 10),
                          Expanded(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Row(
                                      children: <Widget>[
                                        Text(
                                          _chatList[index]
                                              .authorBasicInfo
                                              .realname,
                                          style: TextStyle(fontSize: 18),
                                        ),
                                        SizedBox(width: 5),
                                        openPrescriptionStatus != 0
                                            ? Tag(
                                                text:
                                                    openPrescriptionStatus == 2
                                                        ? '已开处方'
                                                        : '未开处方',
                                                bgColor:
                                                    openPrescriptionStatus == 2
                                                        ? Colors.green
                                                        : Colors.red,
                                                fontSize: 10,
                                              )
                                            : Container()
                                      ],
                                    ),
                                    _judgeReadNum(_chatList[index].unreadNum)
                                  ],
                                ),
                                Text(
                                  _chatList[index].abstract,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      color: Colors.grey, fontSize: 14),
                                )
                              ],
                            ),
                          ),
                          SizedBox(width: 10),
                        ],
                      ),
                    ),
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) => ChatDetailPage(
                          openPrescriptionStatus: openPrescriptionStatus,
                          chatID: _chatList[index].chatID,
                        ),
                      ));
                    },
                  ),
                ),
                buttons: <Widget>[
                  LeftScrollItem(
                    text: '删除',
                    color: Colors.red,
                    onTap: () {
                      _removeChat(index, _chatList[index].chatID);
                    },
                  ),
                ],
              );
            },
          ),
        ],
      ),
    );
  }
}
